package com.bawei.module_visitor.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.bawei.lib_common.base.BaseViewModel
import com.bawei.lib_common.base.state.Failed
import com.bawei.lib_common.base.state.Loading
import com.bawei.lib_common.base.state.RequestEvent
import com.bawei.lib_common.base.state.Success
import com.bawei.module_visitor.model.VisitorAddBody
import com.bawei.module_visitor.model.VisitorModelItem
import com.bawei.module_visitor.model.VisitorStateModel
import com.bawei.module_visitor.repository.VisitorRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class VisitorViewModel@Inject constructor(
    private val mRepository: VisitorRepository
) : BaseViewModel() {
    //预约来访列表
    private val _visitorEvent = MutableSharedFlow<RequestEvent>()
    val visitorEvent get() = _visitorEvent.asSharedFlow()
    var visitorList: MutableList<VisitorModelItem> = mutableListOf()
    //预约来访数据集合
    private val _stateList = MutableLiveData<List<VisitorStateModel>>()
    val stateList: LiveData<List<VisitorStateModel>> get() = _stateList
    //创建预约来访
    private val _visitorAddEvent = MutableSharedFlow<RequestEvent>()
    val visitorAddEvent get() = _visitorAddEvent.asSharedFlow()
    fun getVisitorApply() {
        execute(
            mRepository.getVisitorApply(),
            onStart = {
                _visitorEvent.emit(Loading)
            },
            onError = {
                _visitorEvent.emit(Failed(it))
            },
            onFinish = {
                visitorList.clear()
                visitorList.addAll(it.data)
                _visitorEvent.emit(Success)
            }
        )
    }
    // 模拟网络请求获取访客状态列表
    fun loadStateList() {
        viewModelScope.launch {
            // 模拟网络延迟（可选）
            delay(500)
            // 本地数据
            val localData = listOf(
                VisitorStateModel(0, "全部状态"),
                VisitorStateModel(1, "待审核"),
                VisitorStateModel(2, "已通过"),
                VisitorStateModel(3, "驳回"),
                VisitorStateModel(4, "已完成"),
            )
            _stateList.value = localData // 更新 LiveData
        }
    }
    //创建预约来访
    fun getVisitorApplyAdd(visitorAddBody: VisitorAddBody) {
        execute(
            mRepository.getVisitorApplyAdd(visitorAddBody),
            onStart = {
                _visitorAddEvent.emit(Success)
            },
            onError = {
                _visitorAddEvent.emit(Failed(it))
            },
            onFinish = {
                _visitorAddEvent.emit(Success)
            }
        )
    }
}